package com.ericsson.enap.modules.autoCheck.task;

import com.alibaba.fastjson.JSONArray;
import com.ericsson.common.mapper.JsonMapper;
import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.FileUtil;
import com.ericsson.common.util.Jdk8DateUtils;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.autoCheck.entity.AlarmMessage;
import com.ericsson.enap.modules.autoCheck.entity.AutoCheck;
import com.ericsson.enap.modules.autoCheck.entity.AutocheckMaxtime;
import com.ericsson.enap.modules.autoCheck.entity.AutocheckParam;
import com.ericsson.enap.modules.autoCheck.entity.NetAutoCheck;
import com.ericsson.enap.modules.autoCheck.entity.VisExcel;
import com.ericsson.enap.modules.autoCheck.entity.VisExcelModuleDetail;
import com.ericsson.enap.modules.autoCheck.service.AutocheckParamService;
import com.ericsson.enap.modules.autoCheck.service.EopsAlarmPlatformService;
import com.ericsson.enap.modules.autoCheck.service.EopsTemplateScheduleService;
import com.ericsson.enap.modules.autoCheck.thread.AutoCheckExecuteCmdThread;
import com.ericsson.enap.modules.autoCheck.service.IEopsTemplateExecuteService;
import com.ericsson.enap.modules.enm.entity.EnipEnmKpiAlarmCondition;
import com.ericsson.enap.modules.enm.service.IEnipEnmKpiAlarmConditionService;
import com.ericsson.enap.modules.procLog.entity.EnipAlarmPlatformConfig;
import com.ericsson.enap.modules.procLog.entity.EnipAlarmPlatformMonitor;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
@Scope("prototype")
public class AutoCheckScheduleTask implements ManualTask {

	private Logger log = LoggerUtils.Logger(LogFileName.EopsAutoCheck);

	@Autowired
	private EopsTemplateScheduleService scheduleService;
	@Autowired
	private EopsAlarmPlatformService eopsAlarmPlatformService;
	@Autowired
	private AutocheckParamService autocheckParamService;

	@Autowired
	private KafkaTemplate<String, String> kafkaTemplate;

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private EpcDictService epcDictService;

	@Value("${collectorAddress}")
	private String collectorAddress;
	@Value("${TpXmlPathTxt}")
	private String TpXmlPathTxt;

	private String interval;

	private String templateTypes;

	@Autowired
	private IEopsTemplateExecuteService autoCheckParseTemplate;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	private IEnipEnmKpiAlarmConditionService enipEnmKpiAlarmConditionService;

	public void setTemplateTypes(String templateTypes) {
		this.templateTypes = templateTypes;
	}

	public void setInterval(String interval) {
		this.interval = interval;
	}

	@Override
	public void execute() {

		log.info(this + "================EopsTemplateScheduleTask  start  interval:"+interval+"=====");
		try {
			String fetchDate = Jdk8DateUtils.now().formatDateTime("yyyy-MM-dd HH:mm:00");
			//查询3类业务模板集合
			List<VisExcel> bizTemplates = scheduleService.getBizTemplates(templateTypes);

			//过滤掉非当前执行周期的模板
			List<VisExcel> curIntervalTemplates = bizTemplates.stream().filter(e -> Integer.valueOf(interval).equals(e.getEcycle())).collect(Collectors.toList());
			//周期下的模板为0则退出
			if(curIntervalTemplates.isEmpty()){
				log.info("==============interval:" + interval + " template size is 0 ,task exeture end");
				return;
			}
			//将模板内相关数据写入json文件
			String ids = curIntervalTemplates.stream().map(e -> String.valueOf(e.getId())).collect(Collectors.joining(","));
			log.info("===========ids:"+ids);
			List<VisExcelModuleDetail> moduleDetailList = scheduleService.getModuleDetailsByExcelIds(ids);

			System.out.println(moduleDetailList.size());


			writeToJsonFile(moduleDetailList,TpXmlPathTxt);

			//查询需要执行的网元集合
			List<NetAutoCheck> workingElements = scheduleService.getWorkingElementsByIP(collectorAddress);
			System.out.println(workingElements.size());

			Map<Integer, NetAutoCheck> workingElementsMap = workingElements.stream().collect(Collectors.toMap(NetAutoCheck::getId, e -> e));

			Map<Integer,List<VisExcelModuleDetail>> netExecuteTemplates = rebuildNetAndTemplate(workingElements,moduleDetailList);

			CountDownLatch latch = new CountDownLatch(netExecuteTemplates.size());
			log.info("initial = " + interval + "==========CountDownLatch size:" + netExecuteTemplates.size());

			//对告警模板单独处理，如果有告警配置则说明是告警模板
			EnipAlarmPlatformConfig config = new EnipAlarmPlatformConfig();
			config.setAlarmBusinessType(2L);
			List<EnipAlarmPlatformConfig> configList =  eopsAlarmPlatformService.getAlarmPlatformConfigList(config);

			List<AutocheckParam> paramList = autocheckParamService.getAutocheckParam();

			//查询指标告警
			EnipEnmKpiAlarmCondition enipEnmKpiAlarmCondition=new EnipEnmKpiAlarmCondition();
			enipEnmKpiAlarmCondition.setStatus(1);
			List<EnipEnmKpiAlarmCondition> enipEnmKpiAlarmConditions=enipEnmKpiAlarmConditionService.selectEnipEnmKpiAlarmConditionList(enipEnmKpiAlarmCondition);

			for (Map.Entry<Integer, List<VisExcelModuleDetail>> entry : netExecuteTemplates.entrySet()) {

				AutoCheckExecuteCmdThread executeCmdThread = new AutoCheckExecuteCmdThread(workingElementsMap.get(entry.getKey()),entry.getValue(),scheduleService,latch,fetchDate,log,TpXmlPathTxt,moduleDetailList,configList,curIntervalTemplates,paramList,mongoTemplate,autoCheckParseTemplate,enipEnmKpiAlarmConditions,rabbitTemplate,interval);
				Thread t = new Thread(executeCmdThread);
				t.start();
			}
			latch.await();

			//更新每个excel 的最大时间
			Map<Integer, AutocheckMaxtime> timeMap = scheduleService.listAutoCheckMaxtime().stream().collect(Collectors.toMap(AutocheckMaxtime::getExcelId, e->e));
			for(VisExcel excel : curIntervalTemplates) {

				AutocheckMaxtime autocheckMaxtime = timeMap.get(excel.getId());
				if (autocheckMaxtime == null) {
					AutocheckMaxtime time = new AutocheckMaxtime();
					time.setExcelId(excel.getId());
					time.setMaxTime(fetchDate);
					scheduleService.insertAutoCheckMaxtime(time);
				} else {
					autocheckMaxtime.setMaxTime(fetchDate);
					scheduleService.updateAutoCheckMaxtime(autocheckMaxtime);
				}
			}


			//清除历史告警
			String cleanDate = DateUtils.beforNumDay(new Date(),-180);  //清除1年前的数据
			System.out.println("清除"+cleanDate+"之前的数据");
			scheduleService.cleanAutoCheck(cleanDate);
			//清除巡检指标数据
			deleteMongodbData(new Date());

			log.info("===== all sub thread run end! =====");
			log.info("initial = " + interval + "================= task run end  ========");
			//定时任务执行后开始新线程查询最新告警，并且发送mq
		} catch (Exception e) {
			log.error("error===="+ e.getMessage()+"====",e);
		}
	}


	/**
	 * 删除过期数据
	 * @param now
	 */
	private void deleteMongodbData(Date now){
		EpcDict epcDict=new EpcDict();
		epcDict.setKeyName("VGCKPIMONGODBTIME");
		epcDict= epcDictService.selectEpcDict(epcDict);
		if(null!=epcDict&&!"".equals(epcDict.getKeyValue())) {
			String deleteTime = DateUtils.getStatisTime(Integer.parseInt(epcDict.getKeyValue())*1440+30,now,"yyyy-MM-dd HH:mm:00");
			log.info("deleteTime-------------------------------:"+deleteTime);
			Query query = Query.query(Criteria.where("dateTime").lte(deleteTime));
			mongoTemplate.remove(query,"autocheck_16_amf");
			mongoTemplate.remove(query,"autocheck_16_smf");
			mongoTemplate.remove(query,"autocheck_16_upf");
		}
	}


	public static void writeToJsonFile(List<VisExcelModuleDetail> moduleDetailList,String fileRootPath) {

		Map<String,List<Object>> jsonMap = new HashMap<>();
		for(VisExcelModuleDetail moduleDetail : moduleDetailList){
			Integer excelId = moduleDetail.getExcelId();
			Integer moduleId = moduleDetail.getModuleId();
			if(jsonMap.containsKey(excelId+"_"+moduleId)){
				jsonMap.get(excelId+"_"+moduleId).add(moduleDetail);
			}else{
				List<Object> jsonList = new ArrayList<>();
				jsonList.add(moduleDetail);
				jsonMap.put(excelId+"_"+moduleId,jsonList);
			}
		}

		for(Map.Entry<String,List<Object>> entry : jsonMap.entrySet()){
			File file = new File(fileRootPath + File.separator + entry.getKey()+".txt");
			file.getParentFile().mkdirs();
			FileUtil.writeToFile(file.getAbsolutePath(), JSONArray.toJSONString(entry.getValue()),false);
		}
	}

	private Map<Integer,List<VisExcelModuleDetail>> rebuildNetAndTemplate(List<NetAutoCheck> workingElements, List<VisExcelModuleDetail> moduleDetailList) {

		//过滤相同模块的元素
		List<VisExcelModuleDetail> subModuleDetailList = new ArrayList<>();
		List<String> excelModuleIds = new ArrayList<>();
		for(VisExcelModuleDetail item : moduleDetailList){
			if(!excelModuleIds.contains(item.getExcelId()+"_"+item.getModuleId())){
				subModuleDetailList.add(item);
				excelModuleIds.add(item.getExcelId()+"_"+item.getModuleId());
			}
		}

		Map<Integer,List<VisExcelModuleDetail>> netExecuteTemplates = new HashMap<>();
		for(VisExcelModuleDetail moduleDetail : subModuleDetailList){
			for(NetAutoCheck net : workingElements){
				if(net.getType().intValue() == Integer.parseInt(moduleDetail.getType())){
					if(netExecuteTemplates.containsKey(net.getId())){
						netExecuteTemplates.get(net.getId()).add(moduleDetail);
					}else{
						List<VisExcelModuleDetail> moduleDetails = new ArrayList<>();
						moduleDetails.add(moduleDetail);
						netExecuteTemplates.put(net.getId(),moduleDetails);
					}
				}
			}
		}
		return netExecuteTemplates;
	}



	public void createMonitorAlarm(String fetchDate,List<NetAutoCheck> workingElements) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				log.info("==============sync mq start=================");
				EnipAlarmPlatformConfig config = new EnipAlarmPlatformConfig();
				config.setAlarmBusinessType(2L);
				Map<Long,EnipAlarmPlatformConfig> configMap =  eopsAlarmPlatformService.getAlarmPlatformConfigList(config).stream().collect(Collectors.toMap(EnipAlarmPlatformConfig::getId,enipAlarmPlatformConfig ->enipAlarmPlatformConfig));


				EnipAlarmPlatformMonitor monitor = new EnipAlarmPlatformMonitor();
				monitor.setStatus(1);
				monitor.setConfigIds(StringUtils.join(configMap.keySet().toArray(),","));
				//已经存在的告警
				Map<String,EnipAlarmPlatformMonitor> monitorMap = eopsAlarmPlatformService.getMonitorList(monitor).stream().collect(Collectors.toMap(k -> k.getConfigId()+"-"+k.getNetId(),enipAlarmPlatformMonitor -> enipAlarmPlatformMonitor));

				//新告警
				List<AutoCheck> autoCheckList = scheduleService.getCurrentAlarm();
				Map<String, AutoCheck> autoCheckLogMap = autoCheckList.stream().collect(Collectors.toMap(k -> k.getVisexcelId()+"-"+k.getNetId(),autoCheckLog -> autoCheckLog));
				int netCount = workingElements.size();  //需要采集网元个数
				Map<Integer,NetAutoCheck> netMap = scheduleService.getWorkingElementsByIP(collectorAddress).stream().collect(Collectors.toMap(NetAutoCheck::getId, net -> net));
				Map<Integer,NetAutoCheck> allNetMap = scheduleService.getWorkingElementsByIP(null).stream().collect(Collectors.toMap(NetAutoCheck::getId, net -> net));

				List<VisExcel> bizTemplates = scheduleService.getBizTemplates("3");
				Map<Integer, VisExcel> tempMap = bizTemplates.stream().collect(Collectors.toMap(VisExcel::getId, visExcel -> visExcel));

				try {
					for(String logKey : autoCheckLogMap.keySet()) {
						String excelId = logKey.split("-")[0];
						String netId = logKey.split("-")[1];
						String configId = null;
						for(Long configKey : configMap.keySet()) {
							EnipAlarmPlatformConfig conf =configMap.get(configKey);
							if(conf.getTemplateId().longValue() == Long.parseLong(excelId)) {
								configId = ""+configKey;
								break;
							}
						}
						if(configId == null) {
							log.info("=================没有配置:"+excelId+"========================");
							continue;
						}

						EnipAlarmPlatformMonitor monitor1 = monitorMap.get(configId+"-"+netId);
						EnipAlarmPlatformConfig config1 = configMap.get(Long.valueOf(configId));
						if(monitor1 == null &&  netCount>0) {
							NetAutoCheck net = netMap.get(Integer.valueOf(netId));
							AutoCheck checklog = autoCheckLogMap.get(logKey);
							//生成alarmId
							String alarmIdTime = Jdk8DateUtils.now().formatDateTime("yyyyMMddHHmmssSSS");
							String alarmId = "eops"+checklog.getNetType()+alarmIdTime;
							String subObject = pattenSubObject(checklog.getAutoCheckItemList().get(0).getCheckLog());
							String message = createMonitorMessage(alarmId,"11000","1",String.valueOf(net.getId()),net.getName(),subObject,config1);
							//sendAlarm(message);


							monitor1 = new EnipAlarmPlatformMonitor();
							monitor1.setNetId(Long.valueOf(netId));
							monitor1.setConfigId(Long.valueOf(configId));
							monitor1.setAlarmId(alarmId);
							monitor1.setCreateTime(fetchDate);
							monitor1.setStatus(1);
							monitor1.setCreateAlarmMsg(message);
							monitor1.setAlarmLog(checklog.getCheckLog());
							eopsAlarmPlatformService.insertAutoCheckMonitor(monitor1);
							log.info("==============netid:"+config1.getNetType()+"    excelid:"+config1.getTemplateId()+"   AlarmUniqueId："+alarmId+"======产生告警===========");

						}
					}

					for(String mqKey : monitorMap.keySet()) {
						String configId = mqKey.split("-")[0];
						String netId = mqKey.split("-")[1];
						EnipAlarmPlatformConfig config1 = configMap.get(Long.valueOf(configId));
						if(config1 == null) {
							log.info("=================没有配置 :"+configId+"========================");
							continue;
						}
						AutoCheck checkLog = autoCheckLogMap.get(config1.getTemplateId()+"-"+netId);
						if(checkLog == null || netCount<=0) {
							VisExcel excel = tempMap.get(Integer.parseInt(""+(config1.getTemplateId().longValue())));

							NetAutoCheck net = netMap.get(Integer.valueOf(netId));
							if(net == null) {
								net = allNetMap.get(Integer.valueOf(netId));
							}
							EnipAlarmPlatformMonitor mq = monitorMap.get(mqKey);
							AlarmMessage am = (AlarmMessage)JsonMapper.fromJsonString(mq.getCreateAlarmMsg(),AlarmMessage.class);
							System.out.println(am.getObjectName());
							String message = createMonitorMessage(mq.getAlarmId(),"11001","0",String.valueOf(net.getId()),net.getName(),am.getSubObjectUID(),config1);
							//sendAlarm(message);

							EnipAlarmPlatformMonitor mq1 = new  EnipAlarmPlatformMonitor();
							mq1.setUpdateTime(fetchDate);
							mq1.setStatus(0);
							mq1.setCancelAlarmMsg(message);
							mq1.setId(mq.getId());
							eopsAlarmPlatformService.updateAutoCheckMonitor(mq1);
							log.info("==============netid:"+mq.getNetId()+"    excelid:"+(config1.getTemplateId())+"  AlarmUniqueId："+mq.getAlarmId()+"======消除告警===========");
						}

					}
				} catch (Exception e) {

					log.error("error===="+ e.getMessage()+"====",e);
				}
				log.info("==============sync mq end=================");
			}
		}).start();
	}





	/**
	 * enip_alarm_platform_monitor
	 */
	/*public void monitorAlarm(String fetchDate,List<NetAutoCheck> workingElements) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				log.info("==============sync mq start=================");
				EnipAlarmPlatformConfig config = new EnipAlarmPlatformConfig();
				config.setAlarmBusinessType(2L);
				Map<Long,EnipAlarmPlatformConfig> configMap =  eopsAlarmPlatformService.getAlarmPlatformConfigList(config).stream().collect(Collectors.toMap(EnipAlarmPlatformConfig::getId,enipAlarmPlatformConfig ->enipAlarmPlatformConfig));
				EnipAlarmPlatformMonitor monitor = new EnipAlarmPlatformMonitor();
				monitor.setStatus(1);
				monitor.setConfigIds(StringUtils.join(configMap.keySet().toArray(),","));
				Map<String,EnipAlarmPlatformMonitor> monitorMap = eopsAlarmPlatformService.getMonitorList(monitor).stream().collect(Collectors.toMap(k -> k.getConfigId()+"-"+k.getNetId(),enipAlarmPlatformMonitor -> enipAlarmPlatformMonitor));



				Map<String, VisAutoCheckLog> autoCheckLogMap = scheduleService.getCurrentTimeAlarm().stream().collect(Collectors.toMap(k -> k.getExcelId()+"-"+k.getNetId(), visAutoCheckLog -> visAutoCheckLog));
				List<VisExcel> bizTemplates = scheduleService.getBizTemplates("6");
				Map<Integer, VisExcel> tempMap = bizTemplates.stream().collect(Collectors.toMap(VisExcel::getId, visExcel -> visExcel));
				int netCount = workingElements.size();  //需要采集网元个数
				Map<Integer,NetAutoCheck> netMap = scheduleService.getWorkingElementsByIP(collectorAddress).stream().collect(Collectors.toMap(NetAutoCheck::getId, net -> net));
				Map<Integer,NetAutoCheck> allNetMap = scheduleService.getWorkingElementsByIP(null).stream().collect(Collectors.toMap(NetAutoCheck::getId, net -> net));
				try {
					for(String logKey : autoCheckLogMap.keySet()) {
						String excelId = logKey.split("-")[0];
						String netId = logKey.split("-")[1];
						String configId = null;
						for(Long configKey : configMap.keySet()) {
							EnipAlarmPlatformConfig conf =configMap.get(configKey);
							if(conf.getTemplateId().longValue() == Long.parseLong(excelId)) {
								configId = ""+configKey;
								break;
							}
						}
						if(configId == null) {
							log.info("=================没有配置:"+excelId+"========================");
							break;
						}
						EnipAlarmPlatformMonitor monitor1 = monitorMap.get(configId+"-"+netId);
						EnipAlarmPlatformConfig config1 = configMap.get(Long.valueOf(configId));
						if(monitor1 == null &&  netCount>0) {
							//一条新的告警，发送mq  AlarmStatus=1, t_autocheck_mq 插入一条数据
							NetAutoCheck net = netMap.get(Integer.valueOf(netId));
							VisAutoCheckLog checklog = autoCheckLogMap.get(logKey);
							//生成alarmId
							String alarmIdTime = Jdk8DateUtils.now().formatDateTime("yyyyMMddHHmmssSSS");
							String alarmId = "eops"+checklog.getNetType()+alarmIdTime;
							String subObject = pattenSubObject(checklog.getCheckLog());
							String message = createMonitorMessage(alarmId,"11000","1",String.valueOf(net.getId()),net.getName(),subObject,config1);
							sendAlarm(message);

							monitor1 = new EnipAlarmPlatformMonitor();
							monitor1.setNetId(Long.valueOf(netId));
							monitor1.setConfigId(Long.valueOf(configId));
							monitor1.setAlarmId(alarmId);
							monitor1.setCreateTime(fetchDate);
							monitor1.setStatus(1);
							monitor1.setCreateAlarmMsg(message);
							monitor1.setAlarmLog(checklog.getCheckLog());
							eopsAlarmPlatformService.insertAutoCheckMonitor(monitor1);
							log.info("==============netid:"+config1.getNetType()+"    excelid:"+config1.getTemplateId()+"   AlarmUniqueId："+alarmId+"======产生告警===========");
						}

					}

					for(String mqKey : monitorMap.keySet()) {
						String configId = mqKey.split("-")[0];
						String netId = mqKey.split("-")[1];
						EnipAlarmPlatformConfig config1 = configMap.get(Long.valueOf(configId));
						if(config1 == null) {
							log.info("=================没有配置 :"+configId+"========================");
							break;
						}
						VisAutoCheckLog checkLog = autoCheckLogMap.get(config1.getTemplateId()+"-"+netId);
						if(checkLog == null || netCount<=0) {
							VisExcel excel = tempMap.get(Integer.parseInt(""+(config1.getTemplateId().longValue())));

							NetAutoCheck net = netMap.get(Integer.valueOf(netId));
							if(net == null) {
								net = allNetMap.get(Integer.valueOf(netId));
							}
							EnipAlarmPlatformMonitor mq = monitorMap.get(mqKey);
							AlarmMessage am = (AlarmMessage)JsonMapper.fromJsonString(mq.getCreateAlarmMsg(),AlarmMessage.class);
							System.out.println(am.getObjectName());
							String message = createMonitorMessage(mq.getAlarmId(),"11001","0",String.valueOf(net.getId()),net.getName(),am.getSubObjectUID(),config1);
							sendAlarm(message);

							EnipAlarmPlatformMonitor mq1 = new  EnipAlarmPlatformMonitor();
							mq1.setUpdateTime(fetchDate);
							mq1.setStatus(0);
							mq1.setCancelAlarmMsg(message);
							mq1.setId(mq.getId());
							eopsAlarmPlatformService.updateAutoCheckMonitor(mq1);
							log.info("==============netid:"+mq.getNetId()+"    excelid:"+(config1.getTemplateId())+"  AlarmUniqueId："+mq.getAlarmId()+"======消除告警===========");
						}

					}
				} catch (Exception e) {

					log.error("error===="+ e.getMessage()+"====",e);
				}
				log.info("==============sync mq end=================");
			}
		}).start();

	}
*/

	public String createMonitorMessage(String alarmId,String subMessageType,String alarmStatus,String objectUID,String objectName,String subObjectUID, EnipAlarmPlatformConfig config) {
		String alarmSeq = Jdk8DateUtils.now().formatDateTime("yyyyMMddHHmmssSSS");
		String eventTime = Jdk8DateUtils.now().formatDateTime("yyyy-MM-dd HH:mm:ss");
		AlarmMessage message = new AlarmMessage();
		message.setSystemId(config.getSystemid()); //三方系统ID
		message.setMessageType(config.getMessagetype()); //消息分类-一级分类
		message.setSubMessageType(subMessageType); //消息分类-二级分类
		message.setAlarmTitle(config.getAlarmtitle()); //告警标题
		message.setAlarmStatus(alarmStatus); //告警状态 1：活动告警；0：清除告警
		message.setAlarmId(alarmId); //告警ID  产生告警与消除告警ID相同
		message.setAlarmSeq(alarmSeq);//告警上报的消息序号 ,每产生一条告警包括消除告警，会产生唯一序号
		message.setAlarmType(config.getAlarmtype()); //告警类型
		message.setOrigSeverity(config.getOrigseverity()); //原始级别
		message.setEventTime(eventTime);  //告警发生时间
		message.setSpecificProblemID(config.getSpecificproblemid()); //告警问题原因ID。厂家告警ID
		message.setSpecificProblem(config.getSpecificproblem()); //告警问题原因
		message.setObjectType(config.getObjecttype()); //设备类型
		//message.setObjectUID(objectUID); //告警定位对象UID
		message.setObjectUID(objectName+"_"+subObjectUID); //告警定位对象UID
		message.setObjectName(objectName);  //网元名

		/*String subObjectType = "";
		if(!"".equals(subObjectUID)) {
			if(subObjectUID.contains("PL")) {
				subObjectType = "PL板卡";
			} else if(subObjectUID.contains("SC")) {
				subObjectType = "SC板卡";
			}
		}*/
		message.setSubObjectUID(objectName+"_"+subObjectUID); //告警定位子对象UID
		message.setSubObjectType(config.getObjecttype());  //告警对象类型
		message.setSubObjectName(objectName+"_"+subObjectUID); //告警定位子对象啊名称

		message.setVendorName(config.getVendorname()); //厂家
		message.setProvince(config.getProvince()); //省份
		message.setCity(config.getCity()); //地市
		message.setAddInfo("");//告警定位信息 为空可以显示告警正文
		return JsonMapper.toJsonString(message);
	}


	public String pattenSubObject(String str) {
		String result = "";
		String pattern = "<PL-\\d+>|<SC-\\d+>";
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(str);
		while(m.find()) {
			result = m.group();
			result = result.substring(1,result.length()-1);
		}
		return result;
	}

	public void sendAlarm(String alarmMessage) {
		kafkaTemplate.send("ericsson_expert_system", alarmMessage);
	}






	/**
	 * enip_autocheck_mq
	 * @Deprecated
	 */
	/*public void sendAlarmToMq(String fetchDate,List<NetAutoCheck> workingElements) {

		new Thread(new Runnable() {
			@Override
			public void run() {
				log.info("==============sync mq start=================");
				Map<Integer, AutomqDictIms> dictMap = scheduleService.getAutomqDicImsList().stream().collect(Collectors.toMap(AutomqDictIms::getVisexcelId, automqDictIms -> automqDictIms));
				Map<String, VisAutoCheckMq> autocheckmqMap = scheduleService.getAutoCheckMqList().stream().collect(Collectors.toMap(k -> k.getExcelId()+"-"+k.getNetId(), visAutoCheckMq -> visAutoCheckMq));
				Map<String, VisAutoCheckLog> autoCheckLogMap = scheduleService.getCurrentTimeAlarm().stream().collect(Collectors.toMap(k -> k.getExcelId()+"-"+k.getNetId(), visAutoCheckLog -> visAutoCheckLog));
				List<VisExcel> bizTemplates = scheduleService.getBizTemplates("6");
				Map<Integer, VisExcel> tempMap = bizTemplates.stream().collect(Collectors.toMap(VisExcel::getId, visExcel -> visExcel));
				int netCount = workingElements.size();  //需要采集网元个数
				//Map<Long,NetIms> netMap  = scheduleService.getNetImsList().stream().collect(Collectors.toMap(NetIms::getId, net -> net));
				Map<Integer,NetAutoCheck> netMap = scheduleService.getWorkingElementsByIP(collectorAddress).stream().collect(Collectors.toMap(NetAutoCheck::getId, net -> net));
				Map<Integer,NetAutoCheck> allNetMap = scheduleService.getWorkingElementsByIP(null).stream().collect(Collectors.toMap(NetAutoCheck::getId, net -> net));
				try {
					for(String logKey : autoCheckLogMap.keySet()) {
						VisAutoCheckMq mq = autocheckmqMap.get(logKey);
						if(mq == null &&  netCount>0) {
							//一条新的告警，发送mq  AlarmStatus=1, t_autocheck_mq 插入一条数据
							String[] logKeyArr = logKey.split("-");
							if(null != logKeyArr && logKeyArr.length == 2) {
								AutomqDictIms dict = dictMap.get(Integer.parseInt(logKeyArr[0]));
								//VisExcel excel = tempMap.get(Integer.parseInt(logKeyArr[0]));
								if(dict != null) {

									NetAutoCheck net = netMap.get(Integer.valueOf(logKeyArr[1]));

									VisAutoCheckLog checklog = autoCheckLogMap.get(logKey);
									//获取该类型最大编号
									VisAutoCheckMqIdGenerator idGen = scheduleService.getIdByType(checklog.getNetType());
									long maxid = idGen.getIdValue() + 1;
									idGen.setIdValue(maxid);
									String alarmId = dict.getAlarmUniqueId()+"-"+maxid;

									String subObject = pattenSubObject(checklog.getCheckLog());

									String message = createMqMessage(alarmId,"11000","1",String.valueOf(net.getId()),net.getName(),subObject,dict);
									sendAlarm(message);
									mq = new VisAutoCheckMq();
									mq.setNetId(logKeyArr[1]);
									mq.setExcelId(Integer.parseInt(logKeyArr[0]));
									mq.setCreateTime(fetchDate);
									mq.setStatus(1);
									mq.setCreateAlarmMsg(message);
									mq.setNetType(checklog.getNetType());
									mq.setAlarmId(alarmId);
									scheduleService.insertAutoCheckMq(mq);
									//更新最大序号
									scheduleService.updateIdValue(idGen);
									log.info("==============netid:"+mq.getNetId()+"    excelid:"+mq.getExcelId()+"   AlarmUniqueId："+alarmId+"======产生告警===========");
								} else {
									log.error("=================没有配置"+logKeyArr[0]+"========================");
								}

							}
						}
					}

					for(String mqkey: autocheckmqMap.keySet()) {
						VisAutoCheckLog checklog = autoCheckLogMap.get(mqkey);
						if(checklog == null || netCount<=0) {  // 如果取消所有网元采集
							//消除告警，发送mq  AlarmStatus=0  , 修改t_autocheck_mq update_time字段 和status字段
							String[] mqKeyArr = mqkey.split("-");
							if(null != mqKeyArr && mqKeyArr.length == 2) {
								AutomqDictIms dict = dictMap.get(Integer.parseInt(mqKeyArr[0]));
								VisExcel excel = tempMap.get(Integer.parseInt(mqKeyArr[0]));
								if(dict != null) {

									NetAutoCheck net = netMap.get(Integer.valueOf(mqKeyArr[1]));
									if(net == null) {
										net = allNetMap.get(Integer.valueOf(mqKeyArr[1]));
									}
									//发送mq
									VisAutoCheckMq mq = autocheckmqMap.get(mqkey);
									AlarmMessage am = (AlarmMessage)JsonMapper.fromJsonString(mq.getCreateAlarmMsg(),AlarmMessage.class);
									System.out.println(am.getObjectName());
									String message = createMqMessage(mq.getAlarmId(),"11001","0",String.valueOf(net.getId()),net.getName(),am.getSubObjectUID(),dict);
									sendAlarm(message);
									//修改数据库表
									mq.setUpdateTime(fetchDate);
									mq.setStatus(0);
									mq.setCancelAlarmMsg(message);
									scheduleService.updateAutoCheckMq(mq);
									log.info("==============netid:"+mq.getNetId()+"    excelid:"+mq.getExcelId()+"  AlarmUniqueId："+mq.getAlarmId()+"======消除告警===========");

								}else {
									log.error("=================没有配置"+mqKeyArr[0]+"========================");
								}
							}
						}
					}
				} catch (Exception e) {
					log.error("error===="+ e.getMessage()+"====",e);
				}

				log.info("==============sync mq end=================");
			}
		}).start();
	}
*/

	/*public String createMqMessage(String alarmId,String subMessageType,String alarmStatus,String objectUID,String objectName,String subObjectUID, AutomqDictIms dict) {
		String alarmSeq = Jdk8DateUtils.now().formatDateTime("yyyyMMddHHmmss");
		String eventTime = Jdk8DateUtils.now().formatDateTime("yyyy-MM-dd HH:mm:ss");
		AlarmMessage message = new AlarmMessage();
		message.setSystemId(dict.getSystemId()); //三方系统ID
		message.setMessageType(dict.getMessageType()); //消息分类-一级分类
		message.setSubMessageType(subMessageType); //消息分类-二级分类
		message.setAlarmTitle(dict.getAlarmTitle()); //告警标题
		message.setAlarmStatus(alarmStatus); //告警状态 1：活动告警；0：清除告警
		message.setAlarmId(alarmId); //告警ID  产生告警与消除告警ID相同
		message.setAlarmSeq(alarmSeq);//告警上报的消息序号 ,每产生一条告警包括消除告警，会产生唯一序号
		message.setAlarmType(dict.getAlarmType()); //告警类型
		message.setOrigSeverity(dict.getOrigSeverity()); //原始级别
		message.setEventTime(eventTime);  //告警发生时间
		message.setSpecificProblemID(dict.getSpecificProblemID()); //告警问题原因ID。厂家告警ID
		message.setSpecificProblem(dict.getSpecificProblem()); //告警问题原因
		message.setObjectType(dict.getObjectType()); //设备类型
		//message.setObjectUID(objectUID); //告警定位对象UID
		message.setObjectUID(objectName+"_"+subObjectUID); //告警定位对象UID
		message.setObjectName(objectName);  //网元名

		*//*String subObjectType = "";
		if(!"".equals(subObjectUID)) {
			if(subObjectUID.contains("PL")) {
				subObjectType = "PL板卡";
			} else if(subObjectUID.contains("SC")) {
				subObjectType = "SC板卡";
			}
		}*//*
		message.setSubObjectUID(objectName+"_"+subObjectUID); //告警定位子对象UID
		message.setSubObjectType(dict.getObjectType());  //告警对象类型
		message.setSubObjectName(objectName+"_"+subObjectUID); //告警定位子对象啊名称

		message.setVendorName(dict.getVendorName()); //厂家
		message.setProvince(dict.getProvince()); //省份
		message.setCity(dict.getCity()); //地市
		message.setAddInfo("");//告警定位信息 为空可以显示告警正文
		return JsonMapper.toJsonString(message);
	}
*/
}
